import os, sys, zipfile, urllib
from xml.dom import minidom

# Find version number from xml
print 'Reading xbmc-ball-streams version'
dom = minidom.parse(urllib.urlopen('addon.xml'))
version = dom.getElementsByTagName('addon')[0].getAttribute('version')
print 'Version is ' + version

# Create zip file name
zipFilePath = 'xbmc-ball-streams.' + version + '.zip'
print 'Packaging the following files into ' + zipFilePath

# Create file list to add to archive
fileList = []
fileList.append('addon.xml')
fileList.append('changelog.txt')
fileList.append('license.txt')
fileList.append('default.py')
fileList.append('ballstreams.py')
fileList.append('utils.py')
fileList.append('icon.png')
fileList.append('fanart.jpg')

# Append resources directory and all files
for base, dirs, files in os.walk('resources'):
    for file in files:
        filePath = os.path.join(base, file)
        if not '.svn' in filePath:
            fileList.append(filePath)

# Print out the files
print '\n'.join(fileList)

# Create zip file
zipFile = zipfile.ZipFile(zipFilePath, 'w')
for fileName in fileList:
    zipFile.write(fileName, arcname = os.path.join('xbmc-ball-streams', fileName))
zipFile.close()
print 'Zip file created! Testing archive is valid...'

# Test zip file
zipFile = zipfile.ZipFile(zipFilePath, 'r')
result = zipFile.testzip()
if result is not None:
    print 'The zip archive is invalid, problem with file: ' + result
    sys.exit(1)
zipFile.close()

print 'xbmc-ball-streams version ' + version + ' packaged successfully!'
